﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Xml;


namespace SIIV.Installer.Web.Custom
{
    [RunInstaller(true)]
    public partial class CustomInstaller : System.Configuration.Install.Installer
    {
        public CustomInstaller()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
            //establecerConnectionString();
        }

        private void establecerConnectionString()
        {
            string servidor = Context.Parameters["SERVIDOR"];
            string db = Context.Parameters["DB"];
            string usuario = Context.Parameters["USUARIO"];
            string password = Context.Parameters["PASSWORD"];
            bool seguridadIntegrada = Context.Parameters["SEGURIDADINTEGRADA"].Equals("1");
            string webConfig = @Context.Parameters["TARGETDIR"] + "Web.config";

            string connectionString = "metadata=res://*/SIIVDataModel.csdl|res://*/SIIVDataModel.ssdl|res://*/SIIVDataModel.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=";
            foreach (string s in servidor.Split('\\'))
            {
                if (s != string.Empty)
                {
                    connectionString += s + "\\";
                }
            }
            connectionString = connectionString.TrimEnd('\\');
            connectionString += seguridadIntegrada ? string.Format(";Initial Catalog={0};Integrated Security=True;MultipleActiveResultSets=True\"", db) : string.Format(";Initial Catalog={0};User ID={1};Password={2};MultipleActiveResultSets=True\"", db, usuario, password);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(webConfig);
            XmlNode nodo = xmlDoc.SelectSingleNode("/configuration/connectionStrings");
            nodo.ChildNodes[0].Attributes["connectionString"].Value = connectionString;
            xmlDoc.Save(webConfig);
        }
    }
}
